import React, { Component, Fragment } from 'react'
import TodoItem from './TodoItem'
import MyTransition from './MyTransition'
import axios from 'axios'
import './TodoList.css'

// Fragment可以处理如果只是想包裹两个div，而不需要显示div时的情况
class TodoList extends Component {
  constructor(props) {
    super(props)
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleClick = this.handleClick.bind(this)
    this.handleListDel = this.handleListDel.bind(this)
    this.setTodoListInfo = this.setTodoListInfo.bind(this)
    this.state = {
      inputValue: '',
      list: []
    }
  }
  handleInputChange(e) {
    const value = e.target.value
    this.setState(() => ({
      inputValue: value
    }))
  }
  handleClick() {
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue]
    }))
  }
  handleListDel(index) {
    this.setState((prevState) => {
      const list = [...prevState.list]
      list.splice(index, 1)
      return {
        list
      }
    })
  }
  getTodoItem() {
    const context = this
    return (
      context.state.list.map(function (item, index) {
        return (
          <TodoItem
            key={index}
            content={item}
            index={index}
            delItem={context.handleListDel}
          >
          </TodoItem>
        )
      })
    )
  }
  componentWillMount() {
    console.log('parent componentWillMount')
  }
  componentWillReceiveProps() {
    console.log('parent componentWillReceiveProps')
  }
  componentDidMount() {
    console.log('parent componentDidMount')
    axios.get('/api/todolist')
      .then(this.setTodoListInfo)
      .catch((e) => {
        alert('error')
        console.log(e)
      })
  }
  setTodoListInfo(resp) {
    const list = resp.data
    debugger
    this.setState((prevState) => ({
      list
    }))
  }
  shouldComponentUpdate() {
    console.log('parent shouldComponentUpdate')
    return true
  }
  componentWillUpdate() {
    console.log('parent componentWillUpdate')
  }
  componentDidUpdate() {
    console.log('parent componentDidUpdate')
  }
  render() {
    console.log('parent render')
    const arr = [11, 12, 13, 14, 15, 16, 17, 18, 19]
    return (
      <Fragment>
        {/* Fragment 是一个占位符 */}
        <div>
          <label htmlFor='inputarea'>文件名称</label>
          <input
            id='inputarea'
            className='inputClass'
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />
          {arr.map((item, index) => {
            if (item % 2) {
              return (<button onClick={this.handleClick} key={index}>提交-{item}</button>)
            } else {
              return (<div key={index}>不一样的花火{item}</div>)
            }
          })}
        </div>
        <div>
          <ul>{this.getTodoItem()}</ul>
        </div>
        <MyTransition></MyTransition>
      </Fragment>
    )
  }
}

export default TodoList